<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-02-18 16:34:48
 * @Last Modified time: 2023-02-22 10:09:07
 */
namespace app\common\services\store;

use think\facade\Db;
use frank\base\BaseService;
use frank\exception\CommonException;
use app\common\dao\store\OrderRefundDao;
use app\common\services\store\OrderService;
use app\common\services\store\OrderGoodsService;
use app\common\enum\store\order\RefundStatusEnum;
use app\common\enum\pay\RefundSourceEnum;
use app\common\services\pay\RefundService as PayRefundService;
/**
 * 售后
 * Class OrderRefundService
 */
class OrderRefundService extends BaseService
{
    /**
     * OrderRefundService constructor.
     * @param UserAddressDao $dao
     */
    public function __construct(OrderRefundDao $dao)
    {
        $this->dao = $dao;
    }

    public function getOrderRefundDetail($filter)
    {
        $detail = $this->dao->search($filter)->with(['user','express','user_express','order','order_goods','address'])->find();
        if (!$detail) {
            throw new CommonException('售后单不存在');
        }
        return $detail->toArray();
    }

    public function getCount($filter){
        $_this = $this->dao->search($filter);
        return $_this->count();
    }

    /**
     * 获取列表
     */
    public function getOrderRefundList(array $filter = [])
    {
        [$page, $limit] = $this->getPageValue();
        $list = $this->dao->getOrderRefundList($filter,$page, $limit,[],['user','order','order_goods'])->toArray();
        return $list;
    }


    /**
     * 新增售后单记录
     */
    public function createApply($uid,$params)
    { 	
    	$goods = OrderGoodsService::instance()->getOrderGoodsDetail(['id'=>$params['order_goods_id']]);
        $order = OrderService::instance()->getOrderDetail(['id'=>$goods['order_id']]);
    	// 创建新的订单
        Db::startTrans();
        try {
            $data = [
                'order_goods_id' => $params['order_goods_id'],
                'order_id' => $goods['order_id'],
                'user_id' => $uid,
                'type' => $params['type'],
                'apply_desc' => $params['content'],
                'type_desc' => $params['type_desc'],
                'imgs'=> $params['imgs'],
                'status' => RefundStatusEnum::APPLY,
            ];
            $data['delivery_type'] = $order['delivery_type']['value'];
            $this->dao->save($data);
            OrderService::instance()->update($goods['order_id'],[
                'refund_status'=>RefundStatusEnum::APPLY
            ]);
            OrderGoodsService::instance()->update($data['order_goods_id'],[
                'refund_status'=>RefundStatusEnum::APPLY
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            // 回滚事务
            Db::rollback();
            return false;
        }
    }

    /**
     * 售后单审核
     */
    public function audit($params){
        $agree = $params['is_agree'];
        if ($agree == 2 && empty($params['refuse_desc'])) {
            $this->error = '请输入拒绝原因';
            return false;
        }
        $data = [
            'agree_status' => $agree,
        ];

        $detail = $this->getOrderRefundDetail(['id'=>$params['id']]);

        $refundType = $detail['type']['value'];

        $deliveryType = $detail['order']['delivery_type']['value'];
        if($refundType != 3 && $deliveryType == 'express' &&  $agree == 1){
            if (empty($params['address_id'])) {
                $this->error = '请选择退货地址';
                return false;
            }
            $data['refund_address_id'] = $params['address_id'];
        }

        Db::startTrans();
        try {
            // 拒绝申请, 标记售后单状态为已拒绝
            if($agree == 2){
                $data['refuse_desc'] = $params['refuse_desc'];
                $data['status'] = RefundStatusEnum::REJECTED;
            }else{
                $data['status'] = RefundStatusEnum::AFOOT;
            }
            
            // 仅退款处理
            if($agree == 1 && $refundType == 3 && $this->refundPrice($detail,$params['refund_money'])){
                $data['status'] = RefundStatusEnum::COMPLETED;
                $data['refund_money'] = $params['refund_money'];
                $data['refund_time'] = time();
            }
            // 同意换货申请, 标记售后单状态为已完成
            // $params['is_agree'] == 10 && $this['type']['value'] == 20 && $params['status'] = 20;
            // 更新退款单状态
            $this->dao->update($params['id'],$data);
            // 同意售后申请, 记录退货地址
            if ($deliveryType == 1 && $deliveryType == 'express' && $agree == 1) {
                // $model = new OrderRefundAddressM;
                // $model->add($this['order_refund_id'], $params['address_id']);
                // $this->order->is_refund = ( $this->type == 10?30:20);
                // $this->together(['order'])->save();
            }

            OrderService::instance()->update($detail['order_id'],[
                'refund_status'=>$data['status']
            ]);
            OrderGoodsService::instance()->update($detail['order_goods_id'],[
                'refund_status'=>$data['status']
            ]);

            // 事务提交
            Db::commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            Db::collback();
            return false;
        }
    }

    /**
     * 退款
     */
    public function refundPrice($detail,$money = null)
    {
         // 退款金额，如不指定则默认为订单实付款金额
        is_null($money) && $money = $detail['order_goods']['total_pay_price'];
        // 添加退款单
        return PayRefundService::instance()->execute([
            'source'=>RefundSourceEnum::MASTER,
            'source_id'=>$detail['order_id'],
            'order_no'=>$detail['order']['order_no'],
            'order_id'=>$detail['order_id'],
            'pay_price'=>$detail['order_goods']['total_pay_price'],
            'refund_price'=>$money,
            'refund_status'=>3,
        ],$detail['order']['pay_type']['value']);
    }

    /**
     * 取消售后单
     */ 
    public function cancel($data){
        $detail = $this->dao->search([
            'id'=>$data['id']
        ])->find();
        if ($detail['status']['value'] != 1) {
            throw new CommonException('当前状态不可取消');
        }
        // 订单取消事件
        return $this->transaction(function () use ($detail,$data) {

            $statusData['status'] = 5;

            OrderService::instance()->update($detail['order_id'],[
                'refund_status'=>RefundStatusEnum::CANCEL
            ]);
            OrderGoodsService::instance()->update($detail['order_goods_id'],[
                'refund_status'=>RefundStatusEnum::CANCEL
            ]);

            // 更新订单状态
            return $detail->save($statusData);
        });
    }

    /**
     * 用户发货
     */
    public function userDelivery($uid,$data){
        $detail = $this->dao->search([
            'id'=>$data['order_refund_id']
        ])->find();
         if ($detail['user_send_status']) {
            $this->error = '当前售后单不合法，不允许该操作';
            return false;
        }
        if ($data['user_express_id'] <= 0) {
            $this->error = '请选择物流公司';
            return false;
        }
        if (empty($data['user_express_no'])) {
            $this->error = '请填写物流单号';
            return false;
        }
        return $detail->save([
            'user_send_status' => 1,
            'user_send_time' => time(),
            'user_express_id' => (int)$data['user_express_id'],
            'user_express_no' => $data['user_express_no'],
        ]);
    }

    /**
     * 用户已收货 （换货，处理完成）
     */
    public function receipt($id){
        $detail = $this->dao->search([
            'id'=>$id
        ])->find();
        Db::startTrans();
        try {
            
            // 更新退款单状态
            $this->dao->update($id,[
                'user_receipt_status'=>1,
                'status'=>RefundStatusEnum::COMPLETED,
            ]);


            OrderService::instance()->update($detail['order_id'],[
                'refund_status'=>RefundStatusEnum::COMPLETED
            ]);
            OrderGoodsService::instance()->update($detail['order_goods_id'],[
                'refund_status'=>RefundStatusEnum::COMPLETED
            ]);
            // 事务提交
            Db::commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            dump($this->error);die;
            Db::collback();
            return false;
        }
    }

    /**
     * 用户已到店退回商品
     */
    public function arrival($id,$refundMoney = null){
        $detail = $this->dao->search([
            'id'=>$id
        ])->find();
        Db::startTrans();
        try {
            $money =!is_null($refundMoney)?$refundMoney : $detail['order_goods']['total_pay_price'];
            // 退款处理
            $this->refundPrice($detail,$money);
            $data['status'] = RefundStatusEnum::COMPLETED;
            $data['refund_money'] = $money;
            $data['refund_time'] = time();
            $data['user_send_status'] = 1;
            // 更新退款单状态      
            $this->dao->update($id,$data);
            OrderService::instance()->update($detail['order_id'],[
                'refund_status'=>$data['status']
            ]);
            OrderGoodsService::instance()->update($detail['order_goods_id'],[
                'refund_status'=>$data['status']
            ]);

            // 事务提交
            Db::commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            Db::collback();
            return false;
        }
    }
}

